package com.guigu.gulimall.seckill.schedule;

import com.guigu.gulimall.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 秒商品定时上架
 * 每天晚上三点上架    最近三天需要秒杀的商品
 * 当天0：00：00到23：59：59
 * 明天0：00：00到23：59：59
 * 后天0：00：00到23：59：59
 */
@Component
@Slf4j
@EnableScheduling
@Service
public class SeckillSkuSchedule {

    @Autowired
    SeckillService seckillService;
    @Autowired
    RedissonClient redissonClient;

    private final String upload_lock="seckill:upload:lock";


    //TODO 幂等性处理
    @Scheduled(cron = "*/3 * * * * ?")
    public void uploadSeckillSkuLatest3Days(){
        //1.不需要处理重复上架
        log.info("上架秒杀商品信息......");
        //2.处理幂等性
        //获取锁  分布式锁  所的业务执行完，状态已经更新完成。释放锁以后。其他人才会获取到最新的状态
        RLock lock = redissonClient.getLock(upload_lock);
        lock.lock(10, TimeUnit.SECONDS);
        try {
            seckillService.uploadSeckillSkuLatest3Days();
        }finally {
            lock.unlock();
        }
    }
}
